package org.mat.ipaas.ucenter.web.single.modules.system.controller;


import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.mat.framework.lang.dto.MatApiResponse;
import org.mat.ipaas.ucenter.web.single.modules.aop.PermissionData;
import org.mat.ipaas.ucenter.biz.common.config.TenantContext;
import org.mat.ipaas.ucenter.biz.common.constant.CommonConstant;
import org.mat.ipaas.ucenter.biz.common.constant.SymbolConstant;
import org.mat.ipaas.ucenter.biz.common.system.query.QueryGenerator;
import org.mat.ipaas.ucenter.biz.common.system.vo.LoginUser;
import org.mat.ipaas.ucenter.biz.common.util.PasswordUtil;
import org.mat.ipaas.ucenter.web.single.modules.TokenUtils;
import org.mat.ipaas.ucenter.biz.common.util.oConvertUtils;
import org.mat.ipaas.ucenter.biz.config.mybatis.MybatisPlusSaasConfig;
import org.mat.ipaas.ucenter.biz.modules.base.service.BaseCommonService;
import org.mat.ipaas.ucenter.biz.modules.system.entity.*;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysTenantPackService;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysTenantService;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysUserService;
import org.mat.ipaas.ucenter.biz.modules.system.service.ISysUserTenantService;
import org.mat.ipaas.ucenter.biz.modules.system.vo.SysUserTenantVo;
import org.mat.ipaas.ucenter.biz.modules.system.vo.tenant.TenantDepartAuthInfo;
import org.mat.ipaas.ucenter.biz.modules.system.vo.tenant.TenantPackModel;
import org.mat.ipaas.ucenter.biz.modules.system.vo.tenant.TenantPackUser;
import org.mat.ipaas.ucenter.biz.modules.system.vo.tenant.TenantPackUserCount;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * 租户配置信息
 */
@Slf4j
@RestController
@RequestMapping("/sys/tenant")
public class SysTenantController {

    @Autowired
    private ISysTenantService sysTenantService;

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private ISysUserTenantService relationService;

    @Autowired
    private ISysTenantPackService sysTenantPackService;

    @Autowired
    private BaseCommonService baseCommonService;

    /**
     * 获取列表数据
     *
     * @param sysTenant
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@RequiresPermissions("system:tenant:list")
    @PermissionData(pageComponent = "system/TenantList")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public MatApiResponse<IPage<SysTenant>> queryPageList(SysTenant sysTenant, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        MatApiResponse<IPage<SysTenant>> matApiResponse = new MatApiResponse<IPage<SysTenant>>();
        //---author:zhangyafei---date:20210916-----for: 租户管理添加日期范围查询---
        Date beginDate = null;
        Date endDate = null;
        if (oConvertUtils.isNotEmpty(sysTenant)) {
            beginDate = sysTenant.getBeginDate();
            endDate = sysTenant.getEndDate();
            sysTenant.setBeginDate(null);
            sysTenant.setEndDate(null);
        }
        //---author:zhangyafei---date:20210916-----for: 租户管理添加日期范围查询---
        QueryWrapper<SysTenant> queryWrapper = QueryGenerator.initQueryWrapper(sysTenant, req.getParameterMap());
        //---author:zhangyafei---date:20210916-----for: 租户管理添加日期范围查询---
        if (oConvertUtils.isNotEmpty(sysTenant)) {
            queryWrapper.ge(oConvertUtils.isNotEmpty(beginDate), "begin_date", beginDate);
            queryWrapper.le(oConvertUtils.isNotEmpty(endDate), "end_date", endDate);
        }
        //---author:zhangyafei---date:20210916-----for: 租户管理添加日期范围查询---
        Page<SysTenant> page = new Page<SysTenant>(pageNo, pageSize);
        IPage<SysTenant> pageList = sysTenantService.page(page, queryWrapper);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(pageList);
        return matApiResponse;
    }

    /**
     * 获取租户删除的列表
     *
     * @param sysTenant
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping("/recycleBinPageList")
    //@RequiresPermissions("system:tenant:recycleBinPageList")
    public MatApiResponse<IPage<SysTenant>> recycleBinPageList(SysTenant sysTenant, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                               @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        MatApiResponse<IPage<SysTenant>> matApiResponse = new MatApiResponse<IPage<SysTenant>>();
        Page<SysTenant> page = new Page<SysTenant>(pageNo, pageSize);
        IPage<SysTenant> pageList = sysTenantService.getRecycleBinPageList(page, sysTenant);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(pageList);
        return matApiResponse;
    }

    /**
     * 添加
     *
     * @param
     * @return
     */
    //@RequiresPermissions("system:tenant:add")
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public MatApiResponse<SysTenant> add(@RequestBody SysTenant sysTenant) {
        MatApiResponse<SysTenant> matApiResponse = new MatApiResponse();
        if (sysTenantService.getById(sysTenant.getId()) != null) {
            return matApiResponse.fail("该编号已存在!");
        }
        try {
            sysTenantService.saveTenant(sysTenant);
            matApiResponse.success("添加成功！");
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("操作失败");
        }
        return matApiResponse;
    }

    /**
     * 编辑
     *
     * @param
     * @return
     */
    //@RequiresPermissions("system:tenant:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse<SysTenant> edit(@RequestBody SysTenant tenant) {
        MatApiResponse<SysTenant> matApiResponse = new MatApiResponse();
        SysTenant sysTenant = sysTenantService.getById(tenant.getId());
        if (sysTenant == null) {
            return matApiResponse.fail("未找到对应实体");
        }
        if (oConvertUtils.isEmpty(sysTenant.getHouseNumber())) {
            tenant.setHouseNumber(RandomUtil.randomStringUpper(6));
        }
        boolean ok = sysTenantService.updateById(tenant);
        if (ok) {
            matApiResponse.success("修改成功!");
        }
        return matApiResponse;
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    //@RequiresPermissions("system:tenant:delete")
    @RequestMapping(value = "/delete", method = {RequestMethod.DELETE, RequestMethod.POST})
    public MatApiResponse<?> delete(@RequestParam(name = "id", required = true) String id) {
        //------------------------------------------------------------------
        //如果是saas隔离的情况下，判断当前租户id是否是当前租户下的
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            //获取当前用户
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            SysTenant sysTenant = sysTenantService.getById(id);

            String username = "admin";
            String createdBy = sysUser.getUsername();
            if (!sysTenant.getCreateBy().equals(createdBy) && !username.equals(createdBy)) {
                baseCommonService.addLog("未经授权，不能删除非自己创建的租户，租户ID：" + id + "，操作人：" + sysUser.getUsername(), CommonConstant.LOG_TYPE_2, CommonConstant.OPERATE_TYPE_3);
                return MatApiResponse.fail("删除租户失败,当前操作人不是租户的创建人！");
            }
        }
        //------------------------------------------------------------------

        sysTenantService.removeTenantById(id);
        return MatApiResponse.success("删除成功");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    //@RequiresPermissions("system:tenant:deleteBatch")
    @RequestMapping(value = "/deleteBatch", method = RequestMethod.DELETE)
    public MatApiResponse<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        MatApiResponse<?> matApiResponse = new MatApiResponse<>();
        if (oConvertUtils.isEmpty(ids)) {
            matApiResponse.fail("未选中租户！");
        } else {
            String[] ls = ids.split(",");
            // 过滤掉已被引用的租户
            List<Integer> idList = new ArrayList<>();
            for (String id : ls) {
                //------------------------------------------------------------------
                //如果是saas隔离的情况下，判断当前租户id是否是当前租户下的
                if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
                    //获取当前用户
                    LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
                    SysTenant sysTenant = sysTenantService.getById(id);

                    String username = "admin";
                    String createdBy = sysUser.getUsername();
                    if (!sysTenant.getCreateBy().equals(createdBy) && !username.equals(createdBy)) {
                        baseCommonService.addLog("未经授权，不能删除非自己创建的租户，租户ID：" + id + "，操作人：" + sysUser.getUsername(), CommonConstant.LOG_TYPE_2, CommonConstant.OPERATE_TYPE_3);
                        return MatApiResponse.fail("删除租户失败,当前操作人不是租户的创建人！");
                    }
                }
                //------------------------------------------------------------------

                Long userCount = sysTenantService.countUserLinkTenant(id);
                if (userCount == 0) {
                    idList.add(Integer.parseInt(id));
                }
            }
            if (idList.size() > 0) {
                sysTenantService.removeByIds(idList);
                if (ls.length == idList.size()) {
                    matApiResponse.success("删除成功！");
                } else {
                    matApiResponse.success("部分删除成功！（被引用的租户无法删除）");
                }
            } else {
                matApiResponse.fail("选择的租户都已被引用，无法删除！");
            }
        }
        return matApiResponse;
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryById", method = RequestMethod.GET)
    public MatApiResponse<SysTenant> queryById(@RequestParam(name = "id", required = true) String id) {
        MatApiResponse<SysTenant> matApiResponse = new MatApiResponse<SysTenant>();
        if (oConvertUtils.isEmpty(id)) {
            matApiResponse.fail("参数为空！");
        }
        //------------------------------------------------------------------------------------------------
        //获取登录用户信息
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】, admin给特权可以管理所有租户
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL && !"admin".equals(sysUser.getUsername())) {
            Integer loginSessionTenant = oConvertUtils.getInt(TenantContext.getTenant());
            if (loginSessionTenant != null && !loginSessionTenant.equals(Integer.valueOf(id))) {
                matApiResponse.fail("无权限访问他人租户！");
                return matApiResponse;
            }
        }
        //------------------------------------------------------------------------------------------------
        SysTenant sysTenant = sysTenantService.getById(id);
        if (sysTenant == null) {
            matApiResponse.fail("未找到对应实体");
        } else {
            matApiResponse.setData(sysTenant);
            matApiResponse.setSuccess(true);
        }
        return matApiResponse;
    }


    /**
     * 查询有效的 租户数据
     *
     * @return
     */
    //@RequiresPermissions("system:tenant:queryList")
    @RequestMapping(value = "/queryList", method = RequestMethod.GET)
    public MatApiResponse<List<SysTenant>> queryList(@RequestParam(name = "ids", required = false) String ids) {
        MatApiResponse<List<SysTenant>> matApiResponse = new MatApiResponse<List<SysTenant>>();
        LambdaQueryWrapper<SysTenant> query = new LambdaQueryWrapper<>();
        query.eq(SysTenant::getStatus, 1);
        if (oConvertUtils.isNotEmpty(ids)) {
            query.in(SysTenant::getId, ids.split(","));
        }
        //此处查询忽略时间条件
        List<SysTenant> ls = sysTenantService.list(query);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(ls);
        return matApiResponse;
    }

    /**
     * 产品包分页列表查询
     *
     * @param sysTenantPack
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/packList")
    //@RequiresPermissions("system:tenant:packList")
    public MatApiResponse<IPage<SysTenantPack>> queryPackPageList(SysTenantPack sysTenantPack,
                                                                  @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                  @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                  HttpServletRequest req) {
        QueryWrapper<SysTenantPack> queryWrapper = QueryGenerator.initQueryWrapper(sysTenantPack, req.getParameterMap());
        Page<SysTenantPack> page = new Page<SysTenantPack>(pageNo, pageSize);
        IPage<SysTenantPack> pageList = sysTenantPackService.page(page, queryWrapper);
        List<SysTenantPack> records = pageList.getRecords();
        if (null != records && records.size() > 0) {
            pageList.setRecords(sysTenantPackService.setPermissions(records));
        }
        return MatApiResponse.success(pageList);
    }

    /**
     * 创建租户产品包
     *
     * @param sysTenantPack
     * @return
     */
    @PostMapping(value = "/addPackPermission")
    //@RequiresPermissions("system:tenant:add:pack")
    public MatApiResponse<String> addPackPermission(@RequestBody SysTenantPack sysTenantPack) {
        sysTenantPackService.addPackPermission(sysTenantPack);
        return MatApiResponse.success("创建租户产品包成功");
    }

    /**
     * 创建租户产品包
     *
     * @param sysTenantPack
     * @return
     */
    @PutMapping(value = "/editPackPermission")
    //@RequiresPermissions("system:tenant:edit:pack")
    public MatApiResponse<String> editPackPermission(@RequestBody SysTenantPack sysTenantPack) {
        sysTenantPackService.editPackPermission(sysTenantPack);
        return MatApiResponse.success("修改租户产品包成功");
    }

    /**
     * 批量删除用户菜单
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/deletePackPermissions")
    //@RequiresPermissions("system:tenant:delete:pack")
    public MatApiResponse<String> deletePackPermissions(@RequestParam(value = "ids") String ids) {
        sysTenantPackService.deletePackPermissions(ids);
        return MatApiResponse.success("删除租户产品包成功");
    }


    //===========【低代码应用，前端专用接口 —— 加入限制只能维护和查看自己拥有的租户】==========================================================

    /**
     * 查询当前用户的所有有效租户【低代码应用专用接口】
     *
     * @return
     */
    @RequestMapping(value = "/getCurrentUserTenant", method = RequestMethod.GET)
    public MatApiResponse<Map<String, Object>> getCurrentUserTenant() {
        MatApiResponse<Map<String, Object>> matApiResponse = new MatApiResponse<Map<String, Object>>();
        try {
            LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
            //update-begin---author:wangshuai ---date:20221223  for：[QQYUN-3371]租户逻辑改造，改成关系表------------
            List<Integer> tenantIdList = relationService.getTenantIdsByUserId(sysUser.getId());
            Map<String, Object> map = new HashMap(5);
            if (null != tenantIdList && tenantIdList.size() > 0) {
                //update-end---author:wangshuai ---date:20221223  for：[QQYUN-3371]租户逻辑改造，改成关系表------------
                // 该方法仅查询有效的租户，如果返回0个就说明所有的租户均无效。
                List<SysTenant> tenantList = sysTenantService.queryEffectiveTenant(tenantIdList);
                map.put("list", tenantList);
            }
            matApiResponse.setSuccess(true);
            matApiResponse.setData(map);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            matApiResponse.fail("查询失败！");
        }
        return matApiResponse;
    }

    /**
     * 邀请用户【低代码应用专用接口】
     *
     * @param ids
     * @param phone
     * @return
     */
    @PutMapping("/invitationUserJoin")
    //@RequiresPermissions("system:tenant:invitation:user")
    public MatApiResponse<String> invitationUserJoin(@RequestParam("ids") String ids, @RequestParam("phone") String phone) {
        sysTenantService.invitationUserJoin(ids, phone);
        return MatApiResponse.success("邀请用户成功");
    }

    /**
     * 获取用户列表数据【低代码应用专用接口】
     *
     * @param user
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @RequestMapping(value = "/getTenantUserList", method = RequestMethod.GET)
    //@RequiresPermissions("system:tenant:user:list")
    public MatApiResponse<IPage<SysUser>> getTenantUserList(SysUser user,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            @RequestParam(name = "userTenantId") String userTenantId,
                                                            HttpServletRequest req) {
        MatApiResponse<IPage<SysUser>> matApiResponse = new MatApiResponse<>();
        Page<SysUser> page = new Page<>(pageNo, pageSize);
        Page<SysUser> pageList = relationService.getPageUserList(page, Integer.valueOf(userTenantId), user);
        matApiResponse.setSuccess(true);
        matApiResponse.setData(pageList);
        return matApiResponse;
    }

    /**
     * 请离用户租户【低代码应用专用接口】
     *
     * @param userIds
     * @param tenantId
     * @return
     */
    @PutMapping("/leaveTenant")
    //@RequiresPermissions("system:tenant:leave")
    public MatApiResponse<String> leaveTenant(@RequestParam("userIds") String userIds,
                                              @RequestParam("tenantId") String tenantId) {
        MatApiResponse<String> matApiResponse = new MatApiResponse<>();
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL && !"admin".equals(sysUser.getUsername())) {
            Integer loginSessionTenant = oConvertUtils.getInt(TenantContext.getTenant());
            if (loginSessionTenant != null && !loginSessionTenant.equals(Integer.valueOf(tenantId))) {
                matApiResponse.fail("无权限访问他人租户！");
                return matApiResponse;
            }
        }
        sysTenantService.leaveTenant(userIds, tenantId);
        return MatApiResponse.success("请离成功");
    }

    /**
     * 编辑（只允许修改自己拥有的租户）【低代码应用专用接口】
     *
     * @param
     * @return
     */
    @RequestMapping(value = "/editOwnTenant", method = {RequestMethod.PUT, RequestMethod.POST})
    public MatApiResponse<SysTenant> editOwnTenant(@RequestBody SysTenant tenant, HttpServletRequest req) {
        MatApiResponse<SysTenant> matApiResponse = new MatApiResponse();
        String tenantId = TokenUtils.getTenantIdByRequest(req);
        if (!tenantId.equals(tenant.getId().toString())) {
            return matApiResponse.fail("无权修改他人租户！");
        }

        SysTenant sysTenant = sysTenantService.getById(tenant.getId());
        if (sysTenant == null) {
            return matApiResponse.fail("未找到对应实体");
        }
        if (oConvertUtils.isEmpty(sysTenant.getHouseNumber())) {
            tenant.setHouseNumber(RandomUtil.randomStringUpper(6));
        }
        boolean ok = sysTenantService.updateById(tenant);
        if (ok) {
            matApiResponse.success("修改成功!");
        }
        return matApiResponse;
    }

    /**
     * 创建租户并且将用户保存到中间表【低代码应用专用接口】
     *
     * @param sysTenant
     */
    @PostMapping("/saveTenantJoinUser")
    public MatApiResponse<Integer> saveTenantJoinUser(@RequestBody SysTenant sysTenant) {
        MatApiResponse<Integer> matApiResponse = new MatApiResponse<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //------------------------------------------------------------------------------------------------
        //是否开启系统管理模块的多租户数据隔离【SAAS多租户模式】
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            //---author:scott---date:20220111-----for: 限制免费用户只能创建两个租户--
            Integer count = sysTenantService.countCreateTenantNum(sysUser.getUsername());
            if (count > 2) {
                Set<String> roles = sysUserService.getUserRolesSet(sysUser.getUsername());
                //创建一个付费角色 paymember
                if (roles == null || (!roles.contains("paymember") && !roles.contains("admin"))) {
                    return matApiResponse.fail("免费用户最多创建两个租户!");
                }
            }
            //---author:scott---date:20220111-----for:  限制免费用户只能创建两个租户--
        }
        //------------------------------------------------------------------------------------------------
        Integer tenantId = sysTenantService.saveTenantJoinUser(sysTenant, sysUser.getId());
        matApiResponse.setSuccess(true);
        matApiResponse.setMessage("创建成功");
        matApiResponse.setData(tenantId);
        return matApiResponse;
    }

    /**
     * 加入租户通过门牌号【低代码应用专用接口】
     *
     * @param sysTenant
     */
    @PostMapping("/joinTenantByHouseNumber")
    public MatApiResponse<Integer> joinTenantByHouseNumber(@RequestBody SysTenant sysTenant) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        Integer tenantId = sysTenantService.joinTenantByHouseNumber(sysTenant, sysUser.getId());
        MatApiResponse<Integer> matApiResponse = new MatApiResponse<>();
        if (tenantId != 0) {
            matApiResponse.setMessage("申请租户成功");
            matApiResponse.setSuccess(true);
            matApiResponse.setData(tenantId);
            return matApiResponse;
        } else {
            matApiResponse.setMessage("该门牌号不存在");
            matApiResponse.setSuccess(false);
            return matApiResponse;
        }
    }

    //update-begin---author:wangshuai ---date:20230107  for：[QQYUN-3725]申请加入租户，审核中状态增加接口------------

    /**
     * 分页获取租户用户数据(vue3用户租户页面)【低代码应用专用接口】
     *
     * @param pageNo
     * @param pageSize
     * @param userTenantStatus
     * @param type
     * @param req
     * @return
     */
    @GetMapping("/getUserTenantPageList")
    //@RequiresPermissions("system:tenant:tenantPageList")
    public MatApiResponse<IPage<SysUserTenantVo>> getUserTenantPageList(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                        @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                                        @RequestParam(name = "userTenantStatus") String userTenantStatus,
                                                                        @RequestParam(name = "type", required = false) String type,
                                                                        SysUser user,
                                                                        HttpServletRequest req) {
        Page<SysUserTenantVo> page = new Page<SysUserTenantVo>(pageNo, pageSize);
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String tenantId = oConvertUtils.getString(TenantContext.getTenant(), "0");
        IPage<SysUserTenantVo> list = relationService.getUserTenantPageList(page, Arrays.asList(userTenantStatus.split(SymbolConstant.COMMA)), user, Integer.valueOf(tenantId));
        return MatApiResponse.success(list);
    }

    /**
     * 通过用户id获取租户列表【低代码应用专用接口】
     *
     * @param userTenantStatus 关系表的状态
     * @return
     */
    @GetMapping("/getTenantListByUserId")
    //@RequiresPermissions("system:tenant:getTenantListByUserId")
    public MatApiResponse<List<SysUserTenantVo>> getTenantListByUserId(@RequestParam(name = "userTenantStatus", required = false) String userTenantStatus) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        List<String> list = null;
        if (oConvertUtils.isNotEmpty(userTenantStatus)) {
            list = Arrays.asList(userTenantStatus.split(SymbolConstant.COMMA));
        }
        //租户状态，用户id,租户用户关系状态
        List<SysUserTenantVo> sysTenant = relationService.getTenantListByUserId(sysUser.getId(), list);
        return MatApiResponse.success(sysTenant);
    }

    /**
     * 更新用户租户关系状态【低代码应用专用接口】
     */
    @PutMapping("/updateUserTenantStatus")
    //@RequiresPermissions("system:tenant:updateUserTenantStatus")
    public MatApiResponse<String> updateUserTenantStatus(@RequestBody SysUserTenant userTenant) {
        String tenantId = TenantContext.getTenant();
        if (oConvertUtils.isEmpty(tenantId)) {
            return MatApiResponse.fail("未找到当前租户信息");
        }
        relationService.updateUserTenantStatus(userTenant.getUserId(), tenantId, userTenant.getStatus());
        return MatApiResponse.success("更新用户租户状态成功");
    }

    /**
     * 注销租户【低代码应用专用接口】
     *
     * @param sysTenant
     * @return
     */
    @PutMapping("/cancelTenant")
    //@RequiresPermissions("system:tenant:cancelTenant")
    public MatApiResponse<String> cancelTenant(@RequestBody SysTenant sysTenant, HttpServletRequest request) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        SysTenant tenant = sysTenantService.getById(sysTenant.getId());
        if (null == tenant) {
            return MatApiResponse.fail("未找到当前租户信息");
        }
        if (!sysUser.getUsername().equals(tenant.getCreateBy())) {
            return MatApiResponse.fail("无权限，只能注销自己创建的租户！");
        }
        SysUser userById = sysUserService.getById(sysUser.getId());
        String loginPassword = request.getParameter("loginPassword");
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), loginPassword, userById.getSalt());
        if (!passwordEncode.equals(userById.getPassword())) {
            return MatApiResponse.fail("密码不正确");
        }
        sysTenantService.removeById(sysTenant.getId());
        return MatApiResponse.success("注销成功");
    }
    //update-end---author:wangshuai ---date:20230107  for：[QQYUN-3725]申请加入租户，审核中状态增加接口------------

    /**
     * 获取租户用户不同状态下的数量【低代码应用专用接口】
     *
     * @return
     */
    @GetMapping("/getTenantStatusCount")
    public MatApiResponse<Long> getTenantStatusCount(@RequestParam(value = "status", defaultValue = "1") String status, HttpServletRequest req) {
        String tenantId = TokenUtils.getTenantIdByRequest(req);
        if (null == tenantId) {
            return MatApiResponse.fail("未找到当前租户信息");
        }
        LambdaQueryWrapper<SysUserTenant> query = new LambdaQueryWrapper<>();
        query.eq(SysUserTenant::getTenantId, tenantId);
        query.eq(SysUserTenant::getStatus, status);
        long count = relationService.count(query);
        return MatApiResponse.success(count);
    }

    /**
     * 用户取消租户申请【低代码应用专用接口】
     *
     * @param tenantId
     * @return
     */
    @PutMapping("/cancelApplyTenant")
    public MatApiResponse<String> cancelApplyTenant(@RequestParam("tenantId") String tenantId) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        sysTenantService.leaveTenant(sysUser.getId(), tenantId);
        return MatApiResponse.success("取消申请成功");
    }

    //===========【低代码应用，前端专用接口 —— 加入限制只能维护和查看自己拥有的租户】==========================================================

    /**
     * 彻底删除租户
     *
     * @param ids
     * @return
     */
    @DeleteMapping("/deleteLogicDeleted")
    //@RequiresPermissions("system:tenant:deleteTenantLogic")
    public MatApiResponse<String> deleteTenantLogic(@RequestParam("ids") String ids) {
        sysTenantService.deleteTenantLogic(ids);
        return MatApiResponse.success("彻底删除成功");
    }

    /**
     * 还原删除的租户
     *
     * @param ids
     * @return
     */
    @PutMapping("/revertTenantLogic")
    //@RequiresPermissions("system:tenant:revertTenantLogic")
    public MatApiResponse<String> revertTenantLogic(@RequestParam("ids") String ids) {
        sysTenantService.revertTenantLogic(ids);
        return MatApiResponse.success("还原成功");
    }

    /**
     * 退出租户【低代码应用专用接口】
     *
     * @param sysTenant
     * @param request
     * @return
     */
    @DeleteMapping("/exitUserTenant")
    public MatApiResponse<String> exitUserTenant(@RequestBody SysTenant sysTenant, HttpServletRequest request) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //验证用户是否已存在
        Integer count = relationService.userTenantIzExist(sysUser.getId(), sysTenant.getId());
        if (count == 0) {
            return MatApiResponse.fail("此租户下没有当前用户");
        }
        //验证密码
        String loginPassword = request.getParameter("loginPassword");
        SysUser userById = sysUserService.getById(sysUser.getId());
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), loginPassword, userById.getSalt());
        if (!passwordEncode.equals(userById.getPassword())) {
            return MatApiResponse.fail("密码不正确");
        }
        //退出登录
        sysTenantService.exitUserTenant(sysUser.getId(), sysUser.getUsername(), String.valueOf(sysTenant.getId()));
        return MatApiResponse.success("退出租户成功");
    }

    /**
     * 变更租户拥有者【低代码应用专用接口】
     *
     * @param userId
     * @return
     */
    @PostMapping("/changeOwenUserTenant")
    public MatApiResponse<String> changeOwenUserTenant(@RequestParam("userId") String userId) {
        sysTenantService.changeOwenUserTenant(userId);
        return MatApiResponse.success("退出租户成功");
    }

    /**
     * 邀请用户到租户,通过手机号匹配 【低代码应用专用接口】
     *
     * @param phone
     * @return
     */
    @PostMapping("/invitationUser")
    public MatApiResponse<String> invitationUser(@RequestParam(name = "phone") String phone) {
        return sysTenantService.invitationUser(phone);
    }


    /**
     * 获取 租户产品包-3个默认admin的人员数量
     *
     * @param tenantId
     * @return
     */
    @GetMapping("/loadAdminPackCount")
    public MatApiResponse<List<TenantPackUserCount>> loadAdminPackCount(@RequestParam("tenantId") Integer tenantId) {
        List<TenantPackUserCount> list = sysTenantService.queryTenantPackUserCount(tenantId);
        return MatApiResponse.success(list);
    }

    /**
     * 查询租户产品包信息
     *
     * @param packModel
     * @return
     */
    @GetMapping("/getTenantPackInfo")
    public MatApiResponse<TenantPackModel> getTenantPackInfo(TenantPackModel packModel) {
        TenantPackModel tenantPackModel = sysTenantService.queryTenantPack(packModel);
        return MatApiResponse.success(tenantPackModel);
    }


    /**
     * 添加用户和产品包的关系数据
     *
     * @param sysTenantPackUser
     * @return
     */
    @PostMapping("/addTenantPackUser")
    public MatApiResponse<?> addTenantPackUser(@RequestBody SysTenantPackUser sysTenantPackUser) {
        sysTenantService.addBatchTenantPackUser(sysTenantPackUser);
        return MatApiResponse.success("操作成功！");
    }

    /**
     * 从产品包移除用户
     *
     * @param sysTenantPackUser
     * @return
     */
    @PutMapping("/deleteTenantPackUser")
    public MatApiResponse<?> deleteTenantPackUser(@RequestBody SysTenantPackUser sysTenantPackUser) {
        sysTenantService.deleteTenantPackUser(sysTenantPackUser);
        return MatApiResponse.success("操作成功！");
    }


    /**
     * 修改申请状态
     *
     * @param sysTenant
     * @return
     */
    @PutMapping("/updateApplyStatus")
    public MatApiResponse<?> updateApplyStatus(@RequestBody SysTenant sysTenant) {
        SysTenant entity = this.sysTenantService.getById(sysTenant.getId());
        if (entity == null) {
            return MatApiResponse.fail("租户不存在!");
        }
        entity.setApplyStatus(sysTenant.getApplyStatus());
        sysTenantService.updateById(entity);
        return MatApiResponse.success("");
    }


    /**
     * 获取产品包人员申请列表
     *
     * @param tenantId
     * @return
     */
    @GetMapping("/getTenantPackApplyUsers")
    public MatApiResponse<?> getTenantPackApplyUsers(@RequestParam("tenantId") Integer tenantId) {
        List<TenantPackUser> list = sysTenantService.getTenantPackApplyUsers(tenantId);
        return MatApiResponse.success(list);
    }

    /**
     * 个人 申请成为管理员
     *
     * @param sysTenantPackUser
     * @return
     */
    @PostMapping("/doApplyTenantPackUser")
    public MatApiResponse<?> doApplyTenantPackUser(@RequestBody SysTenantPackUser sysTenantPackUser) {
        sysTenantService.doApplyTenantPackUser(sysTenantPackUser);
        return MatApiResponse.success("申请成功！");
    }

    /**
     * 申请通过 成为管理员
     *
     * @param sysTenantPackUser
     * @return
     */
    @PutMapping("/passApply")
    public MatApiResponse<?> passApply(@RequestBody SysTenantPackUser sysTenantPackUser) {
        sysTenantService.passApply(sysTenantPackUser);
        return MatApiResponse.success("操作成功！");
    }

    /**
     * 拒绝申请 成为管理员
     *
     * @param sysTenantPackUser
     * @return
     */
    @PutMapping("/deleteApply")
    public MatApiResponse<?> deleteApply(@RequestBody SysTenantPackUser sysTenantPackUser) {
        sysTenantService.deleteApply(sysTenantPackUser);
        return MatApiResponse.success("");
    }


    /**
     * 进入应用组织页面 查询租户信息及当前用户是否有 管理员的权限--
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/queryTenantAuthInfo", method = RequestMethod.GET)
    public MatApiResponse<TenantDepartAuthInfo> queryTenantAuthInfo(@RequestParam(name = "id", required = true) String id) {
        TenantDepartAuthInfo info = sysTenantService.getTenantDepartAuthInfo(Integer.parseInt(id));
        return MatApiResponse.success(info);
    }

    /**
     * 获取产品包下的用户列表(分页)
     *
     * @param tenantId
     * @param packId
     * @param status
     * @param pageNo
     * @param pageSize
     * @return
     */
    @GetMapping("/queryTenantPackUserList")
    public MatApiResponse<IPage<TenantPackUser>> queryTenantPackUserList(@RequestParam("tenantId") String tenantId,
                                                                         @RequestParam("packId") String packId,
                                                                         @RequestParam("status") Integer status,
                                                                         @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<TenantPackUser> page = new Page<>(pageNo, pageSize);
        IPage<TenantPackUser> pageList = sysTenantService.queryTenantPackUserList(tenantId, packId, status, page);
        return MatApiResponse.success(pageList);
    }
}
